/**
 * websocket对象，等待在页面加载完后初始化连接获取
 */
var ws = null;


/**
 * 浮点数指定保留小数位
 * @param floatvar
 * @param decimals
 * @returns
 */
function changeTwoDecimalFun(floatvar,decimals){  
		 if(decimals == undefined){
	 		decimals = 0;
	 	}
	 
        var f_x = parseFloat(floatvar);  
        if (isNaN(f_x)){  
        	
        	if(decimals == 0){
        		return '0';
        	} else {
        		var value = '0.';
        		for(var i = 1 ; i <= decimals ; i++){
        			value = value + '0';
        		}
        		return value;  
        	}
        }  
        
        var f_x = Math.round(f_x*100)/100;  
        var s_x = f_x.toString();  
        var pos_decimal = s_x.indexOf('.');  
        if(decimals == 0){
        	if (pos_decimal < 0){  
                return s_x;
            } else {
            	var values = s_x.split('.');
            	return values[0];
            }
        } else {
        	if (pos_decimal < 0){  
        		pos_decimal = s_x.length;  
        		s_x += '.';  
        		for(var i =0 ; i < decimals ; i++){
        			s_x += '0';
        		}
        		return s_x;
        	}  else {
        		var value = s_x.subString(0,pos_decimal+decimals);
        		return value;
        	}
        }
       
    }  ;
    
    	
    
    	/**
		 * 清空当前页面动态数据
		 */
		var cleanPageDataFun = function(){
			$('.mpePoint').text('');
			$('.mpePointStartTime').text('');
			$('.mpePointEndTime').text('');
			$('.voting').empty();
			$('#room-wrapper').empty();
		};
		/**
		 * 清空房间基本数据
		 */
		var cleanRoomBaseDataFun = function(){
			$('.mpePoint').text('');
			$('.mpePointStartTime').text('');
			$('.mpePointEndTime').text('');
			$('.voting').empty();
		};
    	
    	/**
		 * 投票数据列表排序,注意，应该先给投票对象给一个排序号，这是为了适应用户投票排序需求的调整
		 * 采用冒泡排序
		 */
		function orderVoteFun(votes){
			for(var i = 0 ; i < votes.length ; i++){
				
				var temp = {};
				for(var j = i+1 ; j < votes.length ; j++){
					var vote1 = votes[i];
					var vote2 = votes[j];
					if(vote1._order > vote2._order){//如果序号大，就往后移动
						temp = vote2;
						votes[j] = vote1;
						votes[i] = vote2;
					}
				}
			}
		}
    	
    	/**
		获取房间信息
	*/
	function getRoomFun(roomId,callback){
		
		$.ajax({
			url:'../room/get.do?roomId='+roomId,
			type:'get',
			dataType:'json',
			success:function(d){
				callback(d);
				
			}
		});
	};
	
	/**
		计算投票数据
	*/
	function computeTotalVoteFun(votes){
		var totalVotes = 0;
		for(var i in votes){
			totalVotes = totalVotes + parseInt(votes[i].count);
		}
		return totalVotes;
	};
	
	/**
		投票
	*/
	function votingFun(voteId,callback){
		$.ajax({
    		url:'../room/voting.do',
    		type:'get',
    		dataType:'json',
    		data:{
    			id:voteId
    		},
    		success:function(d){
    			callback(d);
    		}
    	});
	};
	
	/**
		刷新投票信息
	*/
	function refreshVoteInfoFun(room){
		var totalVote = computeTotalVoteFun(room.votes);
		var votes = d.data.votes;
		for(var i in votes){
			var percent = (votes[i].count / totalVote)*100;
			percent = changeTwoDecimalFun(percent);
			var v = $('.voting').find('div[name="'+votes[i].id+'"]').get(0);
			$(v).find('.voteValue').text(percent+'%');
		}
	};
    	/**
			 * 刷新房间基本信息函数
			 */
			function refreshRoomFun(room){
					
					//设置官方观点
					var mpe = '';
					switch(room.mpe){
					case 'zd':
						mpe = '震荡偏多';
						break;
					case 'd':
						mpe = '多';
						break;
					case 'zk':
						mpe = '震荡偏空';
						break;
					case 'k':
						mpe = '空';
						break;
					default:
						mpe = room.mpe;
						break;
					}
					$('.mpePoint').text(mpe);
					var mydate = new Date();
					var week;
					 switch (mydate.getDay()){
					 case 1: week="星期一"; break;
					 case 2: week="星期二"; break;
					 case 3: week="星期三"; break;
					 case 4: week="星期四"; break;
					 case 5: week="星期五"; break;
					 case 6: week="星期六"; break;
					 default: week="星期天";
					 }
					
					
					
					var  dstr= mydate.getFullYear() + "-" + (mydate.getMonth() + 1) + "-" + mydate.getDate() + '  ' + week;
					$('.mpePointStartTime').text(dstr);
					$('.mpePointEndTime').text(room.endTime);
					
					//将投票信息按客户要求做排序号设置
					for(var i in room.votes){
						switch(room.votes[i].code){
						case 'k':
							room.votes[i]._order = 2;
							break;
						case 'd':
							room.votes[i]._order = 1;
							break;
						case 'zd':
							room.votes[i]._order = 3;
							break;
						case 'zk':
							room.votes[i]._order = 4;
							break;
						}
					}
					//排序
					orderVoteFun(room.votes);
					
					//设置投票信息
					var totalVote = computeTotalVoteFun(room.votes);
					$('.voting').html('');//先将投票位置清空，再设置内容
					for(var i in room.votes){
						var percent = (room.votes[i].count / totalVote)*100;
						percent = changeTwoDecimalFun(percent);
						var colorClass = 'color-text-red';
						if(room.votes[i].code == 'k'){
							colorClass = 'color-text-green';
						} 
						
						var template ='<div class="col-xs-6 vote-line-box" name="'+room.votes[i].id+'">'
				                            +'<div class="col-xs-2 vote-label '+colorClass+'"><h4 >'+room.votes[i].name+'</h4></div>'
				                            +'<div class="col-xs-5 pro-value '+colorClass+' "><h4 class="voteValue">'+percent+'%</h4></div>'
				                            +'<div class="col-xs-5 vote-click">'
				        					+'<i class="icon icon-thumbs-o-up"></i>'
				                            +'</div>'
											+'</div>';

				        var $template = $(template);
				        $template.find('.vote-click').data('data',room.votes[i]);
				        $template.find('.vote-click').click(function(){
				        	var curData = $(this).data('data');
				        	votingFun(curData.id,function(d2){
				        		if(d2.success){
				        			//刷新投票数据，实际是等待服务器端推送刷新
				        		}
				        	});
				        });
				        
				        
				        $('.voting').append($template);
				        
					}
					
				
			};
			
			

		    /**
		     * 重新封装的数据交互模块，基于数据模型刷新页面数据
		     */
		    	
		    	/******房间喊话数据更新******/
		    	function addSpeekDataFun(data){
		    		var $itemTemplate = $('#template .newsBoxTemplate');
		    		loadSlide(data,'room-wrapper',$itemTemplate,'top');
		    	};
		    	
		    	/***房间数据更新**/
		    	function refreshBaseDataFun(data){
		    		refreshRoomFun(data);
		    	};
			
			
			
	
    $(function(){
//		var dragger = getDragger(true,false);
		var curPage = 1;//最新页加载的页号
		var curPageDataArr = [];//最新页数据
		var pageSize  = 10;//分页记录数
		var roomId = '';//当前页面的roomId
		var userInfo = getLocalUserInfo();
		
		var speekDataArr = [];//当前房间全部请求到的喊话数据缓存数组
		//判断如果是解盘老师，则跳转到解盘老师页面
		if(userInfo != null && userInfo._loginStatus && hasRole('jpls',userInfo.roles)){
			window.location.href = 'preciousMetal.html';
			return;
		}
		
		
		
		/**
		 * 分页方式获取房间喊话信息
		 */
		function loadMsgPage(pageNo,pageSize,callback){
			console.log('pageNo : '+pageNo);
			 $.ajax({
			        type : "get",
			        dataType : "JSON",
			        url : "../room/msgPage.do", // 你请求的地址
			        data : {
			            pageSize:pageSize,  // 传过去的页码
			            pageNo:pageNo,
			            roomId:roomId
			        },
			        success : function(data){
			        	callback(data);
			        },
			        error : function(){

			        }
			    });
		};
		
		/**
		 * 获取全部有效房间喊话
		 */
		function loadMsgList(lastTime,callback){
			$.ajax({
				type : "get",
				dataType : "JSON",
				url : "../room/msgList.do", // 你请求的地址
				data : {
					lastTime:lastTime,//同步
					roomId:roomId
				},
				success : function(data){
					callback(data);
				},
				error : function(){
					
				}
			});
		};
		
		
		/**
		 * 刷新页面数据，当进入新的房间，需要调用该函数全页初始化刷新
		 */
		var refreshPageFun = function(roomId){
			
			cleanPageDataFun();//清空当前页面动态数据
			getRoomFun(roomId,function(d){
				if(d.success){
					//刷新房间基本信息
					refreshRoomFun(d.data);
					
					//刷新房间分析信息 设置房间分析信息，
			        curPage = 1;
			        loadMsgPage(curPage,pageSize,function(d){
			        	if(d.success){
			        		var pageCount = d.data.pageCount;
			        		
			        		console.log('pageCount : '+pageCount);

			        		if(pageCount > curPage){
			        			curPage = pageCount;
			        			loadMsgPage(curPage,pageSize,function(dd){
			        				var $itemTemplate = $('#template .newsBoxTemplate');
					        		loadSlide(dd.data.result,'room-wrapper',$itemTemplate,'bottom');
					        		//判断当前记录数如果小于二分之一pageSize,则继续加载一页
					        		if(curPage > 1 && dd.data.result.length < parseInt(pageSize/2)){
					        			curPage--;
					        			loadMsgPage(curPage,pageSize,function(ddd){
					        				var $itemTemplate = $('#template .newsBoxTemplate');
							        		loadSlide(ddd.data.result,'room-wrapper',$itemTemplate,'bottom');
					        			});
					        		}
			        			});
			        		} else {
			        			var $itemTemplate = $('#template .newsBoxTemplate');
				        		loadSlide(d.data.result,'room-wrapper',$itemTemplate,'bottom');
//				        		setScrollBar2Bottom();//将滚动条移动底部
			        		}
			        	}
			        	
			        });
				}
    		});
		};
		
		  //websocket监听服务器数据推送
		    function connect(roomId) {
	            
	            var url1 = 'ws://'+websocketDomain+"/ep-websocket/websocket/roomws?roomId="+roomId;
	            var url2 = 'http://'+websocketDomain+"/ep-websocket/websocket/roomws?roomId="+roomId;
	            if ('WebSocket' in window) {
	                ws = new WebSocket(url1);
	            } else if ('MozWebSocket' in window) {
	                ws = new MozWebSocket(url1);
	            } else {
	                ws = new SockJS(url2);
	            }
//	            ws = new SockJS(url2);
	            
	            ws.onopen = function () {
	            };
	            ws.onmessage = function (event) {
	            	if(event.data=='ok'){
	            	}else{
	            	//数据派发
	            	var data  = JSON.parse(event.data);
	            	var eventType = data._type;
	            	var d = data;//真正的业务数据
	            	switch(eventType){
	            	case 'roomBaseDataRefresh'://房间基本数据更新
	            		break;
	            	case 'roomSpeeked'://房间喊话数据更新
	            		var dataArr = [d];
	            		addSpeekDataFun(dataArr);
	            		break;
	            	case 'roomVoted'://房间喊话数据更新
	            		cleanRoomBaseDataFun();
	            		refreshRoomFun(d);//实际把房间投票和房间信息都刷新了
	            		break;
	            	case 'roomSpeekDataInit'://房间喊话数据初始化加载
	            		break;
	            	case 'roomBaseDataInit'://房间基本数据初始化加载
	            		break;
	            	}
	            	}
	            };
	            ws.onclose = function (event) {
	            };
	        };
	        
	        /**
			获取房间信息并初始化界面
		*/
		initHeader(function(data){//定义菜单点击后的动作
		//	document.title = data.name + '解盘';
			roomId = data.id;
			if(userInfo != null){
				for(var i in userInfo.roles){
					if(userInfo.roles[i] == 'jpls'){//如果是解盘老师，则跳转
						window.location.href = 'preciousMetal.html?roomId='+roomId;
						return;
					}
				}
				
			}
			if(ws){
				ws.close();//关闭旧的
				ws = null;
			}
			refreshPageFun(roomId);
			connect(roomId);
		},
		function(){//页面初始化
			roomId = getSearchParam('roomId');
			if(ws){
				ws.close();//关闭旧的
				ws = null;
			}
			refreshPageFun(roomId);
			connect(roomId);
		});
		
	        
		 $(window).scroll(function () {
	            if(isLoad()){//判断是否达到加载条件，
	            	var $itemTemplate = $('#template .newsBoxTemplate');
			    	
			    	if(curPage > 1){
			    		var $loadBox = $(".load-icon-box");
	            		 $loadBox.find("img").show(0);
	                     $loadBox.show(0);
	                     $loadBox.find("span").text("数据加载中...");
	                     
			    		curPage--;
			    		loadMsgPage(curPage,pageSize,function(d){
			    			if(d.success){
			    				loadSlide(d.data.result,'room-wrapper',$itemTemplate,'bottom');
			    				curPageDataArr = d.data.result;
			    			}
			    			
			    			$loadBox.show(0);
	                         $loadBox.find("img").hide(0);
	                         $loadBox.find("span").text("数据加载完毕！")
			    		});
			    	}
	            	
	            }
	        }); 
			
	});